package serverApp.threads;

import java.util.Date;

public class Sender implements Runnable {

	private static final long STANDARD = 500;
	private static final long LONG = 2000;
	private static final long VERYLONG = 20000;

	SerialConnection mySerial = null;

	static final private char cntrlZ = (char) 26;
	String in, out;
	Thread aThread = null;
	private long delay = STANDARD;
	String recipient = null;
	String message = null;

	private String csca = "+380683201111"; // the message center
	private SerialParameters defaultParameters = new SerialParameters("COM4",
			9600, 0, 0, 8, 1, 0);
	public int step;
	public int status = -1;
	public long messageNo = -1;

	public Sender(String recipient, String message) {

		this.recipient = recipient;
		this.message = message;

	}

	/**
	 * соединится с портом и открыть поток диалога с модемом
	 */
	public int send() throws Exception {

		SerialParameters params = defaultParameters;

		mySerial = new SerialConnection(params);

		mySerial.openConnection();

		aThread = new Thread(this);

		aThread.start();

		return 0;
	}

	/**
	 * выполнять поэтапно процесс отправки сообщения с помощью AT команд
	 */

	public void run() {

		boolean timeOut = false;
		long startTime = (new Date()).getTime();

		while ((step < 7) && (!timeOut)) {
			// проверить на каком этапе мы находимся
			timeOut = ((new Date()).getTime() - startTime) > delay;

			if (timeOut && (step == 1)) {
				step = -1;
				mySerial.send("" + cntrlZ);
			}

			// обработать входящий текст
			String result = mySerial.getIncommingString();

			int expectedResult = -1;

			try {

				switch (step) {
				case 0:

					mySerial.send("atz");
					delay = LONG;
					startTime = (new Date()).getTime();
					break;

				case 1:
					delay = STANDARD;
					mySerial.send("ath0");
					startTime = (new Date()).getTime();
					break;
				case 2:
					expectedResult = result.indexOf("OK");

					if (expectedResult > -1) {
						mySerial.send("at+cmgf=1");
						startTime = (new Date()).getTime();
					} else {
						step = step - 1;
					}
					break;
				case 3:
					expectedResult = result.indexOf("OK");

					if (expectedResult > -1) {
						mySerial.send("at+csca=\"" + csca + "\"");
						startTime = (new Date()).getTime();
					} else {
						step = step - 1;
					}

					break;
				case 4:
					expectedResult = result.indexOf("OK");

					if (expectedResult > -1) {
						mySerial.send("at+cmgs=\"" + recipient + "\"");
						startTime = (new Date()).getTime();
					} else {
						step = step - 1;
					}

					break;
				case 5:
					expectedResult = result.indexOf(">");

					if (expectedResult > -1) {
						mySerial.send(message + cntrlZ);
						startTime = (new Date()).getTime();
					} else {
						step = step - 1;
					}
					delay = VERYLONG;// ждем ответа

					break;

				case 6:
					expectedResult = result.indexOf("OK");
					
					if (expectedResult > -1) {
						int n = result.indexOf("CMGS:");
						result = result.substring(n + 5);
						n = result.indexOf("\n");
						status = 0;
						messageNo = Long.parseLong(result.substring(0, n)
								.trim());

						log("sent message no:" + messageNo);

					} else {
						step = step - 1;
					}

					break;
				}
				step = step + 1;

				aThread.sleep(100);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		mySerial.closeConnection();


		if (timeOut) {
			status = -2;
			log("*** time out at step " + step + "***");
		}
	}

	/**
	 * функция логирования. выводит информацию о дате и имени класса
	 */
	private void log(String s) {
		System.out.println(new java.util.Date() + ":"
				+ this.getClass().getName() + ":" + s);
	}
}